<template>
  <div class="provider-channel-config-list">
    <!-- 页面标题和提示 -->
    <div class="page-header">
      <div class="page-title">
        <h2>渠道配置管理</h2>
        <div class="page-description">
          <span class="provider-info">
            <span class="provider-label">当前服务商：</span>
            <span class="provider-highlight">火金科技</span>
          </span>
          <span class="description-text">管理火金科技旗下各支付渠道的配置信息</span>
        </div>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-form">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="服务商">
          <a-select
            v-model:value="searchForm.providerId"
            placeholder="请选择服务商"
            allowClear
            style="width: 150px"
          >
            <a-select-option v-for="provider in getAllProviders()" :key="provider.id" :value="provider.id">
              {{ provider.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="支付渠道">
          <a-select
            v-model:value="searchForm.channelId"
            placeholder="请选择支付渠道"
            allowClear
            style="width: 150px"
          >
            <a-select-option v-for="channel in getAllChannels()" :key="channel.id" :value="channel.id">
              {{ channel.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="环境类型">
          <a-select
            v-model:value="searchForm.isSandbox"
            placeholder="请选择环境"
            allowClear
            style="width: 120px"
          >
            <a-select-option :value="1">沙箱环境</a-select-option>
            <a-select-option :value="0">生产环境</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allowClear
            style="width: 100px"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button @click="handleReset" style="margin-left: 8px">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <AnyTable
      ref="anyTableRef"
      :table-columns="tableColumns"
      :data-loader="loadTableData"
      :search-params="searchForm"
      :auto-load="true"
    >
      <template #tableActions>
        <a-button type="primary" @click="handleAdd">新增渠道配置</a-button>
        <a-button type="primary" @click="handleDrawerAdd">快速配置</a-button>
      </template>
      <template #tableCell="{ column, record }">
        <template v-if="column.key === 'providerId'">
          <span class="provider-name">
            {{ getProviderNameById(record.providerId) }}
          </span>
        </template>
        <template v-if="column.key === 'channelId'">
          <a-tag color="blue">
            {{ getChannelNameById(record.channelId) }}
          </a-tag>
        </template>
        <template v-if="column.key === 'isSandbox'">
          <a-tag :color="record.isSandbox === 1 ? 'orange' : 'cyan'">
            {{ record.isSandbox === 1 ? '沙箱' : '生产' }}
          </a-tag>
        </template>
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'success' : 'error'">
            {{ record.status === 1 ? '启用' : '禁用' }}
          </a-tag>
        </template>
        <template v-if="column.key === 'baseConfig'">
          <a-tooltip placement="top">
            <template #title>
              <pre>{{ formatJson(record.baseConfig) }}</pre>
            </template>
            <a-button type="link" size="small">查看配置</a-button>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'feeConfig'">
          <a-tooltip placement="top">
            <template #title>
              <pre>{{ formatJson(record.feeConfig) }}</pre>
            </template>
            <a-button type="link" size="small">查看费率</a-button>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'op'">
          <a-space>
            <a-button type="link" size="small" @click="handleView(record)">详情</a-button>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-button type="link" size="small" @click="handleDrawerView(record)">Drawer查看</a-button>
            <a-button type="link" size="small" @click="handleDrawerEdit(record)">Drawer编辑</a-button>
            <a-button
              type="link"
              size="small"
              :danger="record.status === 1"
              @click="handleToggleStatus(record)"
            >
              {{ record.status === 1 ? '禁用' : '启用' }}
            </a-button>
            <a-button type="link" size="small" danger @click="handleDelete(record)">删除</a-button>
          </a-space>
        </template>
      </template>
    </AnyTable>

    <!-- Drawer 组件 -->
    <DrawerDetail
      v-model:visible="drawerDetailVisible"
      :config-data="currentDrawerData"
      @close="handleDrawerClose"
    />

    <DrawerAddOrEdit
      v-model:visible="drawerEditVisible"
      :config-data="currentDrawerData"
      :is-edit="isDrawerEdit"
      @close="handleDrawerClose"
      @submit="handleDrawerSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import type { ProviderChannelConfig } from './ProviderChannelConfig';
import {
  apiProviderChannelConfigFetchList,
  apiProviderChannelConfigDelete,
  apiProviderChannelConfigBatchDelete,
  apiProviderChannelConfigUpdateStatus,
  apiProviderChannelConfigAdd,
  apiProviderChannelConfigEdit
} from './api';
import DrawerDetail from './DrawerDetail.vue';
import DrawerAddOrEdit from './DrawerAddOrEdit.vue';
import AnyTable from '@/components/AnyTable.vue';
import { getChannelNameById, getAllChannels } from '@/constants/channels';
import { getProviderNameById, getAllProviders } from '@/constants/providers';

const router = useRouter();

// AnyTable 引用
const anyTableRef = ref();

// 搜索表单
const searchForm = reactive({
  channelId: undefined,
  isSandbox: undefined,
  status: undefined
});

// Drawer 相关状态
const drawerDetailVisible = ref(false);
const drawerEditVisible = ref(false);
const currentDrawerData = ref<ProviderChannelConfig | null>(null);
const isDrawerEdit = ref(false);

// 表格列定义
const tableColumns = reactive([
  { key: "id", title: "配置ID", dataIndex: "id", width: 80, visible: true },
  { key: "providerId", title: "服务商", dataIndex: "providerId", width: 120, visible: true },
  { key: "channelId", title: "支付渠道", dataIndex: "channelId", width: 140, visible: true },
  { key: "isSandbox", title: "环境类型", dataIndex: "isSandbox", width: 90, visible: true },
  { key: "baseConfig", title: "基础配置", dataIndex: "baseConfig", width: 120, visible: true },
  { key: "feeConfig", title: "费率配置", dataIndex: "feeConfig", width: 120, visible: true },
  { key: "status", title: "配置状态", dataIndex: "status", width: 90, visible: true },
  { key: "createdAt", title: "创建时间", dataIndex: "createdAt", width: 180, visible: false },
  { key: "updatedAt", title: "更新时间", dataIndex: "updatedAt", width: 180, visible: false },
  { key: "op", title: "操作", width: 200, fixed: "right", align: "center", visible: true },
]);

// 格式化JSON显示
const formatJson = (jsonStr: string) => {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2);
  } catch {
    return jsonStr;
  }
};

// AnyTable 数据加载器
const loadTableData = async (params: any) => {
  try {
    const response = await apiProviderChannelConfigFetchList({
      page: params.pageNumber,
      size: params.pageSize,
      ...params
    });

    if (response.success) {
      return {
        records: response.data,
        total: response.total
      };
    } else {
      message.error(response.message || '查询失败');
      return { records: [], total: 0 };
    }
  } catch (error) {
    message.error('查询失败');
    console.error('查询失败:', error);
    return { records: [], total: 0 };
  }
};

// 搜索
const handleSearch = () => {
  anyTableRef.value?.resetTable();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    channelId: undefined,
    isSandbox: undefined,
    status: undefined
  });
  anyTableRef.value?.resetTable();
};

// 新增
const handleAdd = () => {
  router.push({ name: 'ProviderChannelConfigAdd' });
};

// 查看详情
const handleView = (record: ProviderChannelConfig) => {
  router.push({
    name: 'ProviderChannelConfigDetail',
    params: { id: record.id! }
  });
};

// 编辑
const handleEdit = (record: ProviderChannelConfig) => {
  router.push({
    name: 'ProviderChannelConfigEdit',
    params: { id: record.id! }
  });
};

// 删除
const handleDelete = (record: ProviderChannelConfig) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条配置吗？删除后不可恢复。',
    onOk: async () => {
      try {
        const response = await apiProviderChannelConfigDelete(record.id!);
        if (response.success) {
          message.success('删除成功');
          anyTableRef.value?.refreshTable();
        } else {
          message.error(response.message || '删除失败');
        }
      } catch (error) {
        message.error('删除失败');
        console.error('删除失败:', error);
      }
    }
  });
};

// 切换状态
const handleToggleStatus = (record: ProviderChannelConfig) => {
  const newStatus = record.status === 1 ? 0 : 1;
  const action = newStatus === 1 ? '启用' : '禁用';

  Modal.confirm({
    title: `确认${action}`,
    content: `确定要${action}这条配置吗？`,
    onOk: async () => {
      try {
        const response = await apiProviderChannelConfigUpdateStatus(record.id!, newStatus);
        if (response.success) {
          message.success(`${action}成功`);
          anyTableRef.value?.refreshTable();
        } else {
          message.error(response.message || `${action}失败`);
        }
      } catch (error) {
        message.error(`${action}失败`);
        console.error(`${action}失败:`, error);
      }
    }
  });
};

// Drawer 操作方法
const handleDrawerAdd = () => {
  currentDrawerData.value = null;
  isDrawerEdit.value = false;
  drawerEditVisible.value = true;
};

const handleDrawerView = (record: ProviderChannelConfig) => {
  currentDrawerData.value = { ...record };
  drawerDetailVisible.value = true;
};

const handleDrawerEdit = (record: ProviderChannelConfig) => {
  currentDrawerData.value = { ...record };
  isDrawerEdit.value = true;
  drawerEditVisible.value = true;
};

const handleDrawerClose = () => {
  drawerDetailVisible.value = false;
  drawerEditVisible.value = false;
  currentDrawerData.value = null;
};

const handleDrawerSubmit = async (data: ProviderChannelConfig) => {
  try {
    const response = isDrawerEdit.value
      ? await apiProviderChannelConfigEdit(data)
      : await apiProviderChannelConfigAdd(data);

    if (response.success) {
      message.success(isDrawerEdit.value ? '更新成功' : '添加成功');
      drawerEditVisible.value = false;
      anyTableRef.value?.refreshTable();
    } else {
      message.error(response.message || (isDrawerEdit.value ? '更新失败' : '添加失败'));
    }
  } catch (error) {
    message.error(isDrawerEdit.value ? '更新失败' : '添加失败');
    console.error('提交失败:', error);
  }
};
</script>

<style scoped>
.provider-channel-config-list {
  padding: 20px;
}

.search-form {
  background: #f5f5f5;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 6px;
}

.action-bar {
  margin-bottom: 16px;
}

/* 服务商名称样式 - 简洁显示 */
.provider-name {
  font-weight: 500;
  color: #2c3e50;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.page-title h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
}

.page-description {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: 8px;
}

.provider-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.provider-label {
  font-size: 14px;
  color: #666;
}

.provider-highlight {
  font-size: 14px;
  font-weight: 600;
  color: #1890ff;
  background: #e6f7ff;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #91caff;
}

.description-text {
  font-size: 14px;
  color: #8c8c8c;
}
</style>